from app.model.user.wtrees_permission import PermissionModel
from app.model.user.wtrees_group_permission import GroupPermissionModel
from app.serve.wtrees.db import db


class PermissionServer(PermissionModel):
    @classmethod
    def role_group(cls, group_id) -> list:
        """
        传入用户组Id ，根据 Group-Permission关联表 获取 权限列表
        """
        query = db.session.query(GroupPermissionModel.permission_id).filter(
            GroupPermissionModel.group_id == group_id
        )
        result = cls.query.filter_by(soft=True, state=True).filter(cls.id.in_(query))
        permissions = result.all()
        return permissions

    @classmethod
    def role_group_ids(cls, group_ids: list) -> list:
        """
        传入用户组Id列表 ，根据 Group-Permission关联表 获取 权限列表
        """
        query = db.session.query(GroupPermissionModel.permission_id).filter(
            GroupPermissionModel.group_id.in_(group_ids)
        )
        result = cls.query.filter_by(soft=True, state=True).filter(cls.id.in_(query))
        permissions = result.all()
        return permissions

    @classmethod
    def group_permission(cls):
        """ 返回权限管理中的所有视图函数的信息，包含它所属module """

        info_list = cls.query.all()
        infos = list()
        infos_module = {}
        for permission in info_list:
            module = infos_module.get(permission.module, None)
            permission.label = permission['name']
            if module:
                module.append(permission)
            else:
                infos_module.setdefault(permission.module, [permission])
        for index, permission in enumerate(infos_module):
            infos_module[permission]
            data = {
                'id': 1000 + index,
                'label': permission,
                'children': infos_module[permission]
            }
            infos.append(data)

        return infos

    @classmethod
    def select_by_group_ids_and_module(cls, group_ids: list, module) -> list:
        """
        传入用户组的 id 列表 和 权限模块名称，根据 Group-Permission关联表 获取 权限列表
        """
        query = db.session.query(GroupPermissionModel.permission_id).filter(
            GroupPermissionModel.group_id.in_(group_ids)
        )
        result = cls.query.filter_by(soft=True, module=module, mount=True).filter(
            cls.id.in_(query)
        )
        permissions = result.all()
        return permissions
